package com.crayon.util;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;

import com.crayon.account.dao.DAOPhotos;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.account.item.adapter.AdapterGridPhoto;
import com.crayon.account.loader.LoaderSQLPhotos;
import com.crayon.sharemenu.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Date;
import java.util.List;

//import android.widget.RadioGroup.OnCheckedChangeListener;

/**
 * com.crayon.util.CameraCropActivity
 * @author kws
 *
 */
public class ActivityCameraCrop extends FragmentActivity 
implements OnClickListener,
LoaderManager.LoaderCallbacks<List<DAOPhotos>>
,OnItemLongClickListener
,OnItemClickListener
{
	public static int REQUESTCODE_CAMERA=0xff01;
	public static String PARAM_UUID="paramuuid";
	public interface OnCameraCropResult{
		public Bitmap OnCamearResult();
	}
	private static final int PICK_FROM_CAMERA = 0;
	private static final int PICK_FROM_ALBUM = 1;
	private static final int CROP_FROM_CAMERA = 2;

	private Uri mImageCaptureUri;
	private ImageView mPhotoImageView;
	private Button mButton;
	private AdapterGridPhoto mAdpater;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_camera);
		mButton = (Button) findViewById(R.id.button);
		mPhotoImageView = (ImageView) findViewById(R.id.image);
		mButton.setOnClickListener(this);
		mPhotoImageView.setOnClickListener(this);
		
		mAdpater = new AdapterGridPhoto(this);
		GridView gridViewImages = (GridView)findViewById(R.id.gridViewImages);
		gridViewImages.setAdapter(mAdpater);
		gridViewImages.setOnItemLongClickListener(this);
		gridViewImages.setOnItemClickListener(this);

		UIBIND.bindView(this, R.id.button_seg_list, this);
		UIBIND.bindView(this, R.id.button_seg_album, this);
		UIBIND.bindView(this, R.id.button_seg_camera, this);
		getSupportLoaderManager().initLoader(0, null, this);
	}
	
	
	/**
	 */
	private void doTakePhotoAction(){
		/*
		 * http://2009.hfoss.org/Tutorial:Camera_and_Gallery_Demo
		 * http://stackoverflow.com/questions/1050297/how-to-get-the-url-of-the-captured-image
		 * http://www.damonkohler.com/2009/02/android-recipes.html
		 * http://www.firstclown.us/tag/android/
		 */

		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//		String url = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
//		mImageCaptureUri = Uri.fromFile(getFileStreamPath("temp"));
//		mImageCaptureUri = Uri.fromFile(getFileStreamPath("temp"));
		String url = "tmp_" + String.valueOf(System.currentTimeMillis()) + ".jpg";
		mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), url));

		intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, PICK_FROM_CAMERA);
	}
	
	/**
	 */
	private void doTakeAlbumAction(){
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType(android.provider.MediaStore.Images.Media.CONTENT_TYPE);
		startActivityForResult(intent, PICK_FROM_ALBUM);
	}
	
	
	private void saveBitmapToDB(Bitmap photo,Uri uri){
		
		DataBaseManager baseManager = DataBaseManager.getHelper(this);
		try {
			DAOPhotos daoPhotos =new DAOPhotos(getIntent().getStringExtra(PARAM_UUID));
			daoPhotos.setSummary(UTILDate.getYYYYMMDD(new Date()));
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			photo.compress(CompressFormat.PNG, 100, bos);
			daoPhotos.setArrays(bos.toByteArray()); 
			daoPhotos.setUri(uri.toString());
			
			baseManager.getDAOPhotos().create(daoPhotos);
			
		} catch (Exception e) {
			// TODO: handle exception
			GDB.log(getClass(), " FAIL to save bitmap to byte array " + e.getMessage());
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if(resultCode != RESULT_OK){
			return;
		}
		switch(requestCode)
		{
			case CROP_FROM_CAMERA:
			{
				Bundle extras = data.getExtras();
				if(extras != null)
				{
					Bitmap photo = extras.getParcelable("data");
					GDB.log(getClass(), "copy image info " + photo.getWidth() +" \t" + photo.getHeight());
					saveBitmapToDB(photo,mImageCaptureUri);
					mPhotoImageView.setImageBitmap(photo);
				}
//				File f = new File(mImageCaptureUri.getPath());
//				if(f.exists()){
//					f.delete();
//				}
				break;
			}
	
			case PICK_FROM_ALBUM:
				mImageCaptureUri = data.getData();
			case PICK_FROM_CAMERA:
			{
//				BitmapFactory.de
				GDB.log(getClass(), "mImageCaptureUri " + mImageCaptureUri.toString());
//				Bitmap bitmap = DecodeUtils.decode( this, mImageCaptureUri, -1, -1);
				Intent intent = new Intent("com.android.camera.action.CROP");
				intent.setDataAndType(mImageCaptureUri, "image/*");
//				intent.putExtra("outputX", 90);
//				intent.putExtra("outputY", 90);
//				intent.putExtra("aspectX", 1);
//				intent.putExtra("aspectY", 1);
				intent.putExtra("scale", true);
				intent.putExtra("return-data", true);
				startActivityForResult(intent, CROP_FROM_CAMERA);
				break;
			}
		}
	}

	@Override
	public void onClick(View v){
		switch(v.getId()){
		case R.id.button_seg_list:
			getSupportLoaderManager().restartLoader(0, null, this);
			break;
		case R.id.button_seg_album:
			doTakeAlbumAction();
			break;
		case R.id.button_seg_camera:
			doTakePhotoAction();
			break;
		}
	}


	@Override
	public Loader<List<DAOPhotos>> onCreateLoader(int arg0, Bundle arg1) {
		// TODO Auto-generated method stub
		return new LoaderSQLPhotos(this, null);
	}


	@Override
	public void onLoadFinished(Loader<List<DAOPhotos>> arg0,
			List<DAOPhotos> arg1) {
		// TODO Auto-generated method stub
		if(arg1==null &&arg1.size()==0) return;
		
		GDB.log(getClass(), " onLoadFinish" + arg1.size());
		mAdpater.clear();
		mAdpater.addAll(arg1);
		mAdpater.notifyDataSetChanged();
		
	}


	@Override
	public void onLoaderReset(Loader<List<DAOPhotos>> arg0) {
		// TODO Auto-generated method stub
		
	}


//	@Override
//	public void onCheckedChanged(RadioGroup group, int checkedId) {
//		// TODO Auto-generated method stub
//	}


	@Override
	public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// TODO Auto-generated method stub
		DAOPhotos daoPhotos = mAdpater.getItem(position);
		if(daoPhotos!=null){
			try {
				DataBaseManager baseManager = DataBaseManager.getHelper(this);
				baseManager.getDAOPhotos().delete(daoPhotos);
				
			} catch (Exception e) {
				// TODO: handle exception
//				GDB.log(getC);
			} finally{
				getSupportLoaderManager().restartLoader(0, null, this);
			}
		}
		return false;
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub

		DAOPhotos daoPhotos = mAdpater.getItem(position);
		if(daoPhotos!=null){
			try {
				DataBaseManager baseManager = DataBaseManager.getHelper(this);
				daoPhotos.setUuid(getIntent().getStringExtra(PARAM_UUID));
				baseManager.getDAOPhotos().update(daoPhotos);
				
			} catch (Exception e) {
				// TODO: handle exception
				GDB.log(getClass(),"...err save photo " + e.getMessage());
			} finally{
				Intent data =new Intent();
				data.putExtra("data", daoPhotos.getArrays());
				data.putExtra("daophoto", daoPhotos);
				setResult(RESULT_OK, data);
				finish();
			}
		}
	}
}